package lc.二叉树.剑指Offer;

import utils.TreeNode;

/**
 * @description:
 * @author: qian
 * @createDate: 2021/10/30
 */
public class 剑指Offer68I_二叉搜索树的最近公共祖先 {

    public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {

        while (root != null) {
            if (root.val < p.val && root.val < q.val) {
                root = root.right;
            }
            else if (root.val > p.val && root.val > q.val) {
                root = root.left;
            }
            else {
                break;
            }
        }
        return root;
    }
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        if (root.val < p.val && root.val < q.val) {
            return lowestCommonAncestor1(root.right,p,q);
        }
        if (root.val > p.val && root.val > q.val) {
            return lowestCommonAncestor1(root.left,p,q);
        }
        return root;
    }

}
